from bs4 import BeautifulSoup
import lxml.etree as etree

import requests
from datetime import datetime, timedelta, date

from quant.match import Match

GOAL_NUM_RATIO_URL = 'https://trade.500.com/jczq/?playid=270&g=2&date='
HALF_RATIO_URL = 'https://trade.500.com/jczq/?playid=272&g=2&date='
SCORE_RATIO_URL = 'https://trade.500.com/jczq/?playid=271&g=2&date='
WIN_RATIO_URL = 'https://trade.500.com/jczq/?playid=269&g=2&vtype=spf&date='

HEADERS = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'}


def run():
    goal_ratios = read_goal_ratio()
    half_ratios = read_half_ratios()
    score_ratios = read_score_ratios()
    print(f'Goal ratios: {goal_ratios} '
          f'\nHalf ratios: {half_ratios} '
          f'\nScore ratios: {score_ratios}')


def read_goal_ratio(day=0):
    dt = (datetime.now() + timedelta(days=day)).strftime('%Y-%m-%d')
    url = GOAL_NUM_RATIO_URL + dt
    r = requests.get(url=url, headers=HEADERS)
    r.encoding = 'gbk'
    html = etree.HTML(r.text)
    tbody = html.xpath('//*[@id="relativeContainer"]/div/div[3]/table[1]/tbody')
    goal_ratios = {}
    for tr in tbody[0].xpath('.//tr'):
        processname = tr.get('data-processname')
        spans = tr.xpath('.//td')[4].xpath('.//span')
        goal_0_ratio = float(spans[0].text)
        goal_1_ratio = float(spans[1].text)
        goal_2_ratio = float(spans[2].text)
        goal_3_ratio = float(spans[3].text)
        goal_4_ratio = float(spans[4].text)
        goal_5_ratio = float(spans[5].text)
        goal_6_ratio = float(spans[6].text)
        goal_7_ratio = float(spans[7].text)

        goal_result = -1
        p_list = tr.xpath('.//td')[4].xpath('.//p')
        for e in p_list:
            if e.get('class') == "betbtn betbtn-ok":
                goal_result = int(e.get("data-value"))
        goal_ratios[processname] = [goal_0_ratio, goal_1_ratio, goal_2_ratio, goal_3_ratio, goal_4_ratio, goal_5_ratio,
                                    goal_6_ratio, goal_7_ratio, goal_result]

    return goal_ratios


def read_half_ratios(day=0):
    dt = (datetime.now() + timedelta(days=day)).strftime('%Y-%m-%d')
    url = HALF_RATIO_URL + dt
    r = requests.get(url=url, headers=HEADERS)
    r.encoding = 'gbk'
    html = etree.HTML(r.text)
    tbody = html.xpath('//*[@id="relativeContainer"]/div/div[3]/table[1]/tbody')
    half_ratios = {}
    for tr in tbody[0].xpath('.//tr'):
        processname = tr.get('data-processname')
        spans = tr.xpath('.//td')[4].xpath('.//span')
        half_ratio_0 = float(spans[0].text)
        half_ratio_1 = float(spans[1].text)
        half_ratio_2 = float(spans[2].text)
        half_ratio_3 = float(spans[3].text)
        half_ratio_4 = float(spans[4].text)
        half_ratio_5 = float(spans[5].text)
        half_ratio_6 = float(spans[6].text)
        half_ratio_7 = float(spans[7].text)
        half_ratio_8 = float(spans[8].text)

        half_result = "待开奖"
        ps = tr.xpath('.//td')[4].xpath('.//p')
        if (ps[0].get('class') == "betbtn betbtn-ok") and (ps[0].get('data-value') == "3-3"):
            half_result = "胜胜"
        elif (ps[1].get('class') == "betbtn betbtn-ok") and (ps[1].get('data-value') == "3-1"):
            half_result = "胜平"
        elif (ps[2].get('class') == "betbtn betbtn-ok") and (ps[2].get('data-value') == "3-0"):
            half_result = "胜负"
        elif (ps[3].get('class') == "betbtn betbtn-ok") and (ps[3].get('data-value') == "1-3"):
            half_result = "平胜"
        elif (ps[4].get('class') == "betbtn betbtn-ok") and (ps[4].get('data-value') == "1-1"):
            half_result = "平平"
        elif (ps[5].get('class') == "betbtn betbtn-ok") and (ps[5].get('data-value') == "1-0"):
            half_result = "平负"
        elif (ps[6].get('class') == "betbtn betbtn-ok") and (ps[6].get('data-value') == "0-3"):
            half_result = "负胜"
        elif (ps[7].get('class') == "betbtn betbtn-ok") and (ps[7].get('data-value') == "0-1"):
            half_result = "负平"
        elif (ps[8].get('class') == "betbtn betbtn-ok") and (ps[8].get('data-value') == "0-0"):
            half_result = "负负"

        half_ratios[processname] = [half_ratio_0, half_ratio_1, half_ratio_2, half_ratio_3, half_ratio_4, half_ratio_5,
                                    half_ratio_6, half_ratio_7, half_ratio_8,half_result]

    return half_ratios


def read_win_ratios(day=0):
    dt = (datetime.now() + timedelta(days=day)).strftime('%Y-%m-%d')
    url = WIN_RATIO_URL + dt
    ratios = requests.get(url=url, headers=HEADERS)
    ratios.encoding = 'gbk'
    html = etree.HTML(ratios.text)
    tbody = html.xpath('//*[@id="relativeContainer"]/div/div[3]/table[1]/tbody')
    win_ratios = {}
    if (len(tbody) == 0):
        return win_ratios
    bet_tb_tr = tbody[0].xpath('.//tr[@class="bet-tb-tr bet-tb-end" or @class="bet-tb-tr"]')
    # bet_tb_tr = tbody[0].xpath('.//tr[@class="bet-tb-tr"]')
    # bet_tb_tr = bet_tb_tr_end + bet_tb_tr
    leagues = tbody[0].xpath('.//td[@class="td td-evt"]//a')
    home_teams = tbody[0].xpath('.//span[@class="team-l"]//a')
    away_teams = tbody[0].xpath('.//span[@class="team-r"]//a')
    rangqiu_list = tbody[0].xpath('.//td[@class="td td-rang"]//p')
    for i in range(0, len(bet_tb_tr)):
        processname = bet_tb_tr[i].get('data-processname')
        league = leagues[i].text
        home_team = home_teams[i].text
        away_team = away_teams[i].text
        rangqiu = rangqiu_list[2 * i + 1].text

        ratios = {}
        bet_btn_rows = bet_tb_tr[i].xpath('.//td[@class="td td-betbtn"]')
        td_end_time = bet_tb_tr[i].xpath('.//td[@class="td td-endtime"]')
        # 胜平负
        bet_btn_list1 = bet_btn_rows[0].xpath('.//div[@class="betbtn-row itm-rangB1"]')[0].xpath(
            './/p[@class="betbtn" or @class="betbtn betbtn-ok"]')
        bet_btn_list2 = bet_btn_rows[0].xpath('.//div[@class="betbtn-row itm-rangB2"]')[0].xpath(
            './/p[@class="betbtn" or @class="betbtn betbtn-ok"]')

        if (len(bet_btn_list1) > 0):
            ratios["win"] = bet_btn_list1[0].get('data-sp')
            ratios["draw"] = bet_btn_list1[1].get('data-sp')
            ratios["lose"] = bet_btn_list1[2].get('data-sp')
        else:
            ratios["win"] = 0
            ratios["draw"] = 0
            ratios["lose"] = 0

        ratios["rangqiu_win"] = bet_btn_list2[0].get('data-sp')
        ratios["rangqiu_draw"] = bet_btn_list2[1].get('data-sp')
        ratios["rangqiu_lose"] = bet_btn_list2[2].get('data-sp')

        ratios["league"] = league
        ratios["home_team"] = home_team
        ratios["away_team"] = away_team
        ratios["rangqiu"] = rangqiu
        ratios["endtime"] = td_end_time[0].text

        # 赛果
        match_results = bet_tb_tr[i].xpath(".//p[@class='betbtn betbtn-ok']")
        win_ratios[processname] = ratios
        if len(match_results) == 2:
            ratios["result"] = match_results[0].get("data-value")
            ratios["rangqiu_result"] = match_results[1].get("data-value")
    return win_ratios


def read_matches(day=0):
    win_ratios = read_win_ratios(day)
    if (len(win_ratios) == 0):
        return
    goal_ratios = read_goal_ratio(day)
    half_ratios = read_half_ratios(day)
    score_ratios = read_score_ratios(day)
    matches = {}
    for k in win_ratios.keys():
        processname = k
        # if day < 0 and "result" not in win_ratios[processname].keys():
        #     continue
        win_ratio = win_ratios[processname]
        # goal_ratio = goal_ratios[processname]
        # half_ratio = half_ratios[processname]
        # score_ratio = score_ratios[processname]
        match = Match()
        match.no = processname
        match.league = win_ratio['league']
        match.away_team = win_ratio['away_team']
        match.home_team = win_ratio['home_team']
        match.rangqiu = win_ratio['rangqiu']
        match.win = win_ratio['win']
        match.draw = win_ratio['draw']
        match.lose = win_ratio['lose']
        match.rangqiu_win = win_ratio['rangqiu_win']
        match.rangqiu_draw = win_ratio['rangqiu_draw']
        match.rangqiu_lose = win_ratio['rangqiu_lose']
        match.endtime = win_ratio['endtime']
        match.game_date = "2024-" + win_ratio['endtime'].split(" ")[0]
        match.result = 99
        match.rangqiu_result = 99
        if "result" in win_ratio.keys():
            match.result = win_ratio['result']
        if "rangqiu_result" in win_ratio.keys():
            match.rangqiu_result = win_ratio['rangqiu_result']

        match.goal_0 = goal_ratios[processname][0]
        match.goal_1 = goal_ratios[processname][1]
        match.goal_2 = goal_ratios[processname][2]
        match.goal_3 = goal_ratios[processname][3]
        match.goal_4 = goal_ratios[processname][4]
        match.goal_5 = goal_ratios[processname][5]
        match.goal_6 = goal_ratios[processname][6]
        match.goal_7 = goal_ratios[processname][7]
        match.goal_result = goal_ratios[processname][8]
        matches[k] = match
    return matches


def read_score_ratios(day=0):
    dt = (datetime.now() + timedelta(days=day)).strftime('%Y-%m-%d')
    url = SCORE_RATIO_URL + dt
    r = requests.get(url=url, headers=HEADERS)
    r.encoding = 'gbk'
    html = etree.HTML(r.text)
    tbody = html.xpath('//*[@id="relativeContainer"]/div/div[3]/table[1]/tbody')
    score_ratios = {}
    bet_more_wrap_tb_end = tbody[0].xpath('.//tr[@class="bet-more-wrap bet-tb-end hide"]')
    bet_more_wrap = tbody[0].xpath('.//tr[@class="bet-more-wrap"]')
    if (day == 0):
        bet_more_wrap_hide = tbody[0].xpath('.//tr[@class="bet-more-wrap hide"]')
    else:
        bet_more_wrap_hide = tbody[0].xpath('.//tr[@class="bet-more-wrap bet-tb-end hide"]')

    bet_more_wrap = bet_more_wrap_tb_end + bet_more_wrap + bet_more_wrap_hide
    bet_tb_tr_end = tbody[0].xpath('.//tr[@class="bet-tb-tr bet-tb-end"]')
    if (day == 0):
        bet_tb_tr = tbody[0].xpath('.//tr[@class="bet-tb-tr"]')
    else:
        bet_tb_tr = tbody[0].xpath('.//tr[@class="bet-tb-tr bet-tb-end"]')

    bet_tb_tr = bet_tb_tr_end + bet_tb_tr

    for i in range(0, len(bet_tb_tr)):
        processname = bet_tb_tr[i].get('data-processname')
        score_ratios[processname] = {}
        p_list = bet_more_wrap[i].xpath('.//p[@class="sbetbtn"]') + bet_more_wrap[i].xpath(
            './/p[@class="sbetbtn sbetbtn-ok"]')
        for ii in range(0, 31):
            data_sp = p_list[ii].get("data-sp")
            data_value = p_list[ii].get("data-value")
            score_ratios[processname][data_value] = data_sp
    return score_ratios


def read_odds(day=0):
    dt = (datetime.now() + timedelta(days=day)).strftime('%Y-%m-%d')
    url = WIN_RATIO_URL + dt
    ratios = requests.get(url=url, headers=HEADERS)
    ratios.encoding = 'gbk'
    html = etree.HTML(ratios.text)
    tbody = html.xpath('//*[@id="relativeContainer"]/div/div[3]/table[1]/tbody')
    win_ratios = {}
    if (len(tbody) == 0):
        return win_ratios
    bet_tb_tr = tbody[0].xpath('.//tr[@class="bet-tb-tr bet-tb-end" or @class="bet-tb-tr"]')
    # bet_tb_tr = tbody[0].xpath('.//tr[@class="bet-tb-tr"]')
    # bet_tb_tr = bet_tb_tr_end + bet_tb_tr
    leagues = tbody[0].xpath('.//td[@class="td td-evt"]//a')
    home_teams = tbody[0].xpath('.//span[@class="team-l"]//a')
    away_teams = tbody[0].xpath('.//span[@class="team-r"]//a')
    rangqiu_list = tbody[0].xpath('.//td[@class="td td-rang"]//p')
    hrefs = tbody[0].xpath('.//td[@class="td td-data"]//a')
    odd_links = []
    for odd in hrefs:
        if (odd.text == "欧"):
            odd_links.append(odd.get('href'))

    for i in range(0, len(bet_tb_tr)):
        processname = bet_tb_tr[i].get('data-processname')
        league = leagues[i].text
        home_team = home_teams[i].text
        away_team = away_teams[i].text
        rangqiu = rangqiu_list[2 * i + 1].text

        ratios = {}
        bet_btn_rows = bet_tb_tr[i].xpath('.//td[@class="td td-betbtn"]')
        td_end_time = bet_tb_tr[i].xpath('.//td[@class="td td-endtime"]')
        # 胜平负
        bet_btn_list1 = bet_btn_rows[0].xpath('.//div[@class="betbtn-row itm-rangB1"]')[0].xpath(
            './/p[@class="betbtn" or @class="betbtn betbtn-ok"]')
        bet_btn_list2 = bet_btn_rows[0].xpath('.//div[@class="betbtn-row itm-rangB2"]')[0].xpath(
            './/p[@class="betbtn" or @class="betbtn betbtn-ok"]')

        if (len(bet_btn_list1) > 0):
            ratios["win"] = bet_btn_list1[0].get('data-sp')
            ratios["draw"] = bet_btn_list1[1].get('data-sp')
            ratios["lose"] = bet_btn_list1[2].get('data-sp')
        else:
            ratios["win"] = 0
            ratios["draw"] = 0
            ratios["lose"] = 0
        ratios['no'] = processname
        ratios["rangqiu_win"] = bet_btn_list2[0].get('data-sp')
        ratios["rangqiu_draw"] = bet_btn_list2[1].get('data-sp')
        ratios["rangqiu_lose"] = bet_btn_list2[2].get('data-sp')

        ratios["league"] = league
        ratios["home_team"] = home_team
        ratios["away_team"] = away_team
        ratios["rangqiu"] = rangqiu
        ratios["endtime"] = td_end_time[0].text

        # 从百家欧赔读取赔率
        odd_link = odd_links[i]
        odds = requests.get(url=odd_link, headers=HEADERS)
        odds.encoding = 'gbk'
        html2 = etree.HTML(odds.text)
        tds = html2.xpath('//*[@id="1"]/td[3]/table/tbody/tr[1]/td')
        if (len(tds) == 0):
            continue
        win = tds[0].xpath('.//text()')[0]
        draw = tds[1].xpath('.//text()')[0]
        lose = tds[2].xpath('.//text()')[0]
        ratios["win"] = win
        ratios["draw"] = draw
        ratios["lose"] = lose

        # 赛果
        match_results = bet_tb_tr[i].xpath(".//p[@class='betbtn betbtn-ok']")
        win_ratios[processname] = ratios
        if len(match_results) == 2:
            ratios["result"] = match_results[0].get("data-value")
            ratios["rangqiu_result"] = match_results[1].get("data-value")
    return win_ratios


if __name__ == '__main__':
    # read_matches()
    # match_ratios = read_odds()
    run()
    pass
